package com.ydy.file.controller;

import com.ydy.common.BaseController;
import com.ydy.common.constant.Constant;
import com.ydy.common.model.FileInfo;
import com.ydy.common.util.ParamsUtil;
import com.ydy.common.util.RedisUtil;
import com.ydy.common.vo.PageInfo;
import com.ydy.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
import java.util.List;

@RestController
public class FileController extends BaseController {


    @Autowired
    private FileService fileService;

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;

    /**
     * 查询文件列表
     * @param request
     * @return
     */
    @GetMapping("/queryFileInfo")
    public Object queryFileInfo(HttpServletRequest request){
        PageInfo pageInfo = ParamsUtil.getPageInfo(request);
        FileInfo fileInfo = ParamsUtil.getBeanParam(new FileInfo(),request);

        List<FileInfo> fileInfoList = fileService.queryFileInfo(fileInfo,pageInfo);
        pageInfo.setPageResult(fileInfoList);
        return pageInfo;
    }

    /**
     * 删除文件
     * @param fileInfo
     * @return
     */
    @PostMapping("/deleteFile")
    public Object deleteFile (@RequestBody FileInfo fileInfo){
        fileService.deleteFileInfo(fileInfo);
        return retResultVo();
    }

    /**
     * 下载文件
     * @Title: downloadFileInfo
     * @author: dy.yin 2021/4/12 16:43
     * @param: [response, request]
     * @return: java.lang.Object
     * @throws
     */
    @GetMapping("/downloadFileInfo")
    public Object downloadFileInfo(HttpServletResponse response, HttpServletRequest request){
        FileInfo fileInfo = ParamsUtil.getBeanParam(new FileInfo(),request);
        RedisUtil redisUtil = new RedisUtil(redisTemplate);
        String serveUrl = String.valueOf(redisUtil.get(Constant.SERVE_URL));
        writeFileToWeb(request,response,fileInfo.getFileUrl().replace(serveUrl,""));
        return retResultVo();
    }
}
